//
//  ZWStartAVController.swift
//  SwiftFreshBeen
//
//  Created by Apple on 16/12/23.
//  Copyright © 2016年 zhouwnegang. All rights reserved.
//

import UIKit
import SDWebImage
import SnapKit

class ZWStartAVController: UIViewController {
    
    var avModel:ZWStartAdModel?
    var startAdImage:UIImageView?
    var delta:Int = 5
    var timer:Timer?
    
    
    
    lazy var timeLabel:UILabel = UILabel()//创建时间Label
    
    override func loadView() {
       
        self.startAdImage =  UIImageView(frame: ScreenFrame)
        
        self.view = self.startAdImage
            
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        ZWGetDataTool.shared.getStartAdData { (avModel, isSucess) in
            //获取广告页的数据
            self.avModel = avModel;
            
            //刷新UI界面
           self.refreshUI()
         
        }
    }
    
    //MARK:刷新UI界面
    func refreshUI( ) {
      
            guard let imageUrl = URL(string: (self.avModel!.img_name)!) else {
                
                return;
            }
        
            self.startAdImage?.sd_setImage(with: imageUrl)
        
        self.view.addSubview(timeLabel)
        
        
//        let timeDuration = (avModel?.endtime)! - (avModel?.starttime)!//使用时间戳
//        
//        let fmt = DateFormatter()
//        fmt.dateFormat = "HH:mm:ss"
//        
//        let date = Date(timeIntervalSince1970: TimeInterval(timeDuration))
//        
//        let dateString = fmt.string(from: date)

        
         timer = Timer(timeInterval: 1, target: self, selector: #selector(run), userInfo: [], repeats: true)
        RunLoop.current.add(timer!, forMode: .defaultRunLoopMode)
        
        

        timeLabel.text = "\(Int(5))秒后跳转"
        timeLabel.textColor = UIColor.white
        timeLabel.snp.makeConstraints { (make) in
            
            make.top.equalTo(self.view).offset(20)
            make.trailing.equalTo(self.view).offset(-20)
        }
    }
    @objc func run() {
        
        self.delta -= 1  //"\(Int(delta/60))分钟前"
        timeLabel.text = "\(Int(delta))秒后跳转"
        
        if self.delta == 0 {
            
            //发出通知,切换根视图控制器
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: changeRootVC), object: nil)
            
            timer?.invalidate()
            timer = nil
        }
        
        
        print("%@时间在走",timeLabel.text!)
        
    }
    
}
